package cn.cocho.custom.yunCashierDf.uc.service;

import cn.cocho.common.web.app.JsonResultContants;
import cn.cocho.common.web.character.DesEncrypt;
import cn.cocho.common.web.character.StringUtils;
import cn.cocho.common.web.jqgrid.JQGridPage;
import cn.cocho.common.web.jqgrid.JQGridUtils;
import cn.cocho.common.web.utils.JsonResult;
import cn.cocho.common.web.utils.JsonUtils;
import cn.cocho.custom.yunCashierDf.cache.CacheCtrl;
import cn.cocho.custom.yunCashierDf.log.domain.LoginLogInfo;
import cn.cocho.custom.yunCashierDf.log.service.LoginLoginInfoService;
import cn.cocho.custom.yunCashierDf.uc.domain.UcUserInfo;
import cn.cocho.custom.yunCashierDf.uc.domain.UcUserModule;
import cn.cocho.custom.yunCashierDf.utils.AppConstants;
import cn.cocho.custom.yunCashierDf.utils.AppContexts;
import cn.cocho.custom.yunCashierDf.utils.LoggerUtils;
import cn.cocho.custom.yunCashierDf.utils.MailSendUtils;
import cn.cocho.dborm.core.Dborm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 用户操作实现类
 */
@Service("userInfoService")
public class UserInfoService {

    @Autowired
    private LoginLoginInfoService loginLoginInfoService;

    @Autowired
    CacheCtrl cacheCtrl;

    @Autowired
    MailSendUtils mailSendUtils;

    @Autowired
    LoggerUtils logger;

    public JsonResult loginUser(String username, String password) {
        JsonResult result;
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            result = new JsonResult(JsonResultContants.FAIL, "用户名或密码不能为空！");
        } else {
            UcUserInfo ucUserInfo = login(username, password);
            if (ucUserInfo == null) {
                result = new JsonResult(JsonResultContants.FAIL, "用户名或密码错误！");
            } else if (ucUserInfo.getStatus().equals(AppConstants.STATUS_FORBIDDEN)) {
                result = new JsonResult(JsonResultContants.FAIL, "用户被禁用！");
            } else if (ucUserInfo.getStatus().equals(AppConstants.STATUS_NORMOR)) {
                String token = cacheCtrl.getTokenCtrl().addToken(ucUserInfo);
                result = new JsonResult();
                result.setStatusCode(JsonResultContants.SUCCESS);
                result.setStatusMsg("登录成功！");
                result.setToken(token);
                result.setContent(JsonUtils.toJSONString(ucUserInfo));

                LoginLogInfo loginLoginfo = new LoginLogInfo();
                loginLoginfo.setUserId(ucUserInfo.getUserId());
                loginLoginfo.setUserNumber(ucUserInfo.getUsername());

                /*if(ucUserInfo.getRoles().equals("ADMIN")){
                    loginLoginfo.setUserName("管理员");
                }else{
                    MemberInfo memberInfo = memberInfoService.getMemberInfoById(ucUserInfo.getUserId());
                    loginLoginfo.setUserName(memberInfo.getMemberName());
                }*/
                InetAddress addr = null;
                try {
                    addr = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                String ip =addr.getHostAddress().toString();
                loginLoginfo.setLoginIp(ip);
                loginLoginfo.setNote("正常登录");
                loginLoginInfoService.add(loginLoginfo);
            } else {
                result = new JsonResult(JsonResultContants.FAIL, "登录失败！");
            }
        }
        return result;
    }

    public UcUserInfo login(String username, String password) {
        UcUserInfo example = new UcUserInfo();
        example.setUsername(username);
        example.setUserPassword(DesEncrypt.encrypt(password, AppConstants.PASSWORD_DES));
        //return Dborm.getEntity("select * from viewUser where username = '"+example.getUsername().replace("'","")+"' and user_password = '"+example.getUserPassword()+"'", null, UcUserInfo.class);
        return Dborm.getEntity("select * from uc_user_info where username = '"+example.getUsername().replace("'","")+"' and user_password = '"+example.getUserPassword()+"'", null, UcUserInfo.class);
    }

    public JsonResult regUser(UcUserInfo userInfo) {
        JsonResult result = null;
        if (StringUtils.isBlank(userInfo.getEmail()) || StringUtils.isBlank(userInfo.getUsername())) {
            result = new JsonResult(JsonResultContants.FAIL, "用户名或邮箱不能为空！");
        } else {
            UcUserInfo userCheck = regCheck(userInfo);
            if (userCheck != null) {
                if (userCheck.getEmail().equals(userInfo.getEmail())) {
                    result = new JsonResult(JsonResultContants.FAIL, "该邮箱已经被使用！");
                } else if (userCheck.getUsername().equals(userInfo.getUsername())) {
                    result = new JsonResult(JsonResultContants.FAIL, "该用户名已经被使用");
                }
            } else {
                add(userInfo);
                result = new JsonResult(JsonResultContants.SUCCESS, "注册成功！");
            }
        }
        return result;
    }

    public UcUserInfo regCheck(UcUserInfo userInfo) {
        UcUserInfo example = new UcUserInfo();
        example.setUsername(userInfo.getUsername());
        example.setEmail(userInfo.getEmail());
        return Dborm.getEntityByExample(example, false);
    }

    public boolean updatePassword(String password) {
        UcUserInfo userInfo = new UcUserInfo();
        userInfo.setUserId(cacheCtrl.getCurrentUcUserInfo().getUserId());
        userInfo.setUserPassword(DesEncrypt.encrypt(password, AppConstants.PASSWORD_DES));
        return Dborm.replace(userInfo);
    }

    public JsonResult findPasswordUser(String email) {
        JsonResult result;
        if (StringUtils.isBlank(email)) {
            result = new JsonResult(JsonResultContants.FAIL, "邮箱不能为空！");
        } else {
            UcUserInfo userCheck = findPasswordCheck(email);
            if (userCheck != null) {
                String password = DesEncrypt.decrypt(userCheck.getUserPassword(), AppConstants.PASSWORD_DES);
                try {
                    mailSendUtils.sendFindPasswordMail(email, password);
                    result = new JsonResult(JsonResultContants.SUCCESS, "找回密码成功，请查收邮件！");
                } catch (Exception e) {
                    logger.error(e);
                    result = new JsonResult(JsonResultContants.FAIL, "找回密码失败！邮件发送失败，请联系管理员修改你的邮箱！");
                }
            } else {
                result = new JsonResult(JsonResultContants.FAIL, "该邮箱不存在！");
            }
        }
        return result;
    }

    public UcUserInfo findPasswordCheck(String email) {
        UcUserInfo example = new UcUserInfo();
        example.setEmail(email);
        return Dborm.getEntityByExample(example, false);
    }

    public JQGridPage getListByJQgrid(JQGridPage<UcUserInfo> pageJQGrid) {
        pageJQGrid = JQGridUtils.getListByJQgrid(pageJQGrid, UcUserInfo.class, "uc_user_info");
        for (UcUserInfo user : pageJQGrid.getDataRows()) {
            user.init();
            user.setUserPassword(DesEncrypt.decrypt(user.getUserPassword(), AppConstants.PASSWORD_DES));
        }
        return pageJQGrid;
    }

    public JQGridPage getModuleListByJQgrid(JQGridPage<UcUserModule> pageJQGrid) {
        pageJQGrid = JQGridUtils.getListByJQgrid(pageJQGrid, UcUserModule.class, "viewUser");
        for (UcUserModule userModule : pageJQGrid.getDataRows()) {
            userModule.init();
            userModule.setUserPassword(DesEncrypt.decrypt(userModule.getUserPassword(), AppConstants.PASSWORD_DES));
        }
        return pageJQGrid;
    }

    public void update(UcUserInfo userInfo) {
        if (StringUtils.isNotBlank(userInfo.getUserPassword())) {
            userInfo.setUserPassword(DesEncrypt.encrypt(userInfo.getUserPassword(), AppConstants.PASSWORD_DES));
        }
        Dborm.replace(userInfo);
    }

    public void add(UcUserInfo userInfo) {
        userInfo.setUserPassword(DesEncrypt.encrypt(userInfo.getUserPassword(), AppConstants.PASSWORD_DES));
        userInfo.setUserId(StringUtils.getUUID());
        userInfo.setRoles(AppContexts.getSubordinateRoles());
        Dborm.insert(userInfo);
    }

    public UcUserInfo getUserInfoById(String userId) {
        UcUserInfo ucUserInfo = new UcUserInfo();
        ucUserInfo.setUserId(userId);
        return Dborm.getEntityByExample(ucUserInfo, true);
    }

    public boolean insertUserInfo(UcUserInfo ucUserInfo) {
        ucUserInfo.setUserId(StringUtils.getUUID());
        ucUserInfo.setUserPassword(DesEncrypt.encrypt(ucUserInfo.getUserPassword(), AppConstants.PASSWORD_DES));
        return Dborm.insert(ucUserInfo);
    }

    public boolean replaceUserInfo(UcUserInfo ucUserInfo) {
        ucUserInfo.setUserId(ucUserInfo.getUserId());
        ucUserInfo.setUserPassword(DesEncrypt.encrypt(ucUserInfo.getUserPassword(), AppConstants.PASSWORD_DES));
        return Dborm.replace(ucUserInfo);
    }

    public List<UcUserInfo> getUserInfo() {
        String sql = "SELECT * FROM uc_user_info WHERE roles = 'CUSTOMER' AND status = 'STATUS_NORMOR' ORDER BY username ASC ";
        return Dborm.getEntities(sql, null, UcUserInfo.class);
    }

    public List<UcUserInfo> userNameCheck(String userName) {
        String sql = "SELECT * FROM uc_user_info WHERE username = '"+userName+"'";
        return Dborm.getEntities(sql, null, UcUserInfo.class);
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
